package sunyu.controller.shiro.tools;

import com.github.pagehelper.PageHelper;
import org.springframework.ui.Model;
import sunyu.kit.common.StringKit;
import sunyu.mapper.shiro.pojo.Resource;
import sunyu.service.shiro.ResourceService;

import java.util.ArrayList;
import java.util.List;

/**
 * 前台没有使用treeGrid，所以用这个工具自己转换上下级关系列表
 *
 * @author 孙宇
 */
public class ResourceTools {

    /**
     * 将tree格式转换为平滑格式
     *
     * @param list
     * @param tree
     */
    public static void treeToList(List<Resource> list,
                                  List<Resource> tree) {
        for (Resource r : tree) {
            list.add(r);
            if (r.getChildren() != null && r.getChildren().size() > 0) {
                treeToList(list, r.getChildren());
            }
        }
    }

    /**
     * 将平滑格式的列表转换为tree格式
     *
     * @param list
     * @return
     */
    public static List<Resource> listToTree(List<Resource> list) {
        List<Resource> tree = new ArrayList<>();
        for (Resource r : list) {
            boolean mark = false;
            for (Resource r2 : list) {
                if (StringKit.isNotBlank(r.getPid()) && r.getPid().equals(r2.getId())) {
                    mark = true;
                    if (r2.getChildren() == null) {
                        r2.setChildren(new ArrayList<Resource>());
                    }
                    r2.getChildren().add(r);
                    break;
                }
            }
            if (!mark) {
                tree.add(r);
            }
        }
        return tree;
    }

    /**
     * 前台页面需要的资源下拉树
     *
     * @param model
     */
    public static void getResourceTree(Model model,
                                       ResourceService resourceService) {
        PageHelper.orderBy("seq asc");
        List<Resource> l = resourceService.select(null, null);

        List<Resource> tree = ResourceTools.listToTree(l);

        List<Resource> l2 = new ArrayList<>();
        ResourceTools.treeToList(l2, tree);

        model.addAttribute("resources", l2);
    }

}
